<template>
    <div class="ip-config-management">
        <el-card>
            <template #header>
                <div class="card-header">
                    <span>IP配置管理</span>
                    <el-button type="primary" @click="showAddDialog = true">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        添加IP配置
                    </el-button>
                </div>
            </template>

            <!-- 搜索区域 -->
            <div class="search-area">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-input v-model="searchForm.search" placeholder="搜索车间、线别、IP或分档" @keyup.enter="handleSearch"
                            clearable>
                            <template #append>
                                <el-button @click="handleSearch">
                                    <el-icon>
                                        <Search />
                                    </el-icon>
                                </el-button>
                            </template>
                        </el-input>
                    </el-col>
                    <el-col :span="4">
                        <el-select v-model="searchForm.workshop" placeholder="选择车间" clearable @change="handleSearch">
                            <el-option v-for="workshop in workshops" :key="workshop" :label="workshop"
                                :value="workshop" />
                        </el-select>
                    </el-col>
                    <el-col :span="4">
                        <el-button @click="resetSearch">重置</el-button>
                    </el-col>
                </el-row>
            </div>

            <!-- IP配置表格 -->
            <el-table v-loading="loading" :data="ipConfigs" style="width: 100%"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="id" label="序号" width="80" />
                <el-table-column prop="workshop" label="车间" min-width="100" />
                <el-table-column prop="line" label="线别" min-width="100" />
                <el-table-column prop="ip" label="IP" min-width="120" />
                <el-table-column prop="database_path" label="数据库路径" min-width="200" show-overflow-tooltip />
                <el-table-column prop="segment_path" label="分档路径" min-width="200" show-overflow-tooltip />
                <el-table-column prop="current_segment" label="在用分档" min-width="120" />
                <el-table-column prop="is_enabled" label="是否启用" width="100">
                    <template #default="{ row }">
                        <el-tag :type="row.is_enabled ? 'success' : 'danger'">
                            {{ row.is_enabled ? '启用' : '禁用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180" fixed="right">
                    <template #default="{ row }">
                        <el-button size="small" @click="editIpConfig(row)">编辑</el-button>
                        <el-button size="small" type="danger" @click="deleteIpConfig(row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 批量操作 -->
            <div v-if="selectedIpConfigs.length > 0" class="batch-actions">
                <el-alert :title="`已选择 ${selectedIpConfigs.length} 项`" type="info" show-icon :closable="false">
                    <template #default>
                        <el-button size="small" type="danger" @click="batchDelete">
                            批量删除
                        </el-button>
                    </template>
                </el-alert>
            </div>

            <!-- 分页 -->
            <div class="pagination">
                <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.per_page"
                    :page-sizes="[10, 20, 50, 100]" :total="pagination.total"
                    layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <!-- 添加/编辑IP配置对话框 -->
        <el-dialog v-model="showAddDialog" :title="editingIpConfig ? '编辑IP配置' : '添加IP配置'" width="700px"
            @closed="resetForm">
            <el-form ref="ipConfigFormRef" :model="ipConfigForm" :rules="ipConfigRules" label-width="120px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="车间" prop="workshop">
                            <el-input v-model="ipConfigForm.workshop" placeholder="请输入车间名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="线别" prop="line">
                            <el-input v-model="ipConfigForm.line" placeholder="请输入线别" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="IP地址" prop="ip">
                            <el-input v-model="ipConfigForm.ip" placeholder="请输入IP地址" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="在用分档" prop="current_segment">
                            <el-input v-model="ipConfigForm.current_segment" placeholder="请输入在用分档" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="数据库路径" prop="database_path">
                    <el-input v-model="ipConfigForm.database_path" placeholder="请输入数据库路径" />
                </el-form-item>

                <el-form-item label="分档路径" prop="segment_path">
                    <el-input v-model="ipConfigForm.segment_path" placeholder="请输入分档路径" />
                </el-form-item>

                <el-form-item label="启用状态" prop="is_enabled">
                    <el-switch v-model="ipConfigForm.is_enabled" />
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showAddDialog = false">取消</el-button>
                    <el-button type="primary" :loading="submitLoading" @click="submitIpConfig">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const loading = ref(false)
const submitLoading = ref(false)
const showAddDialog = ref(false)
const editingIpConfig = ref(null)
const selectedIpConfigs = ref([])

const ipConfigs = ref([])
const workshops = ref([])

const searchForm = reactive({
    search: '',
    workshop: ''
})

const pagination = reactive({
    page: 1,
    per_page: 10,
    total: 0,
    pages: 0
})

const ipConfigForm = reactive({
    workshop: '',
    line: '',
    ip: '',
    database_path: '',
    segment_path: '',
    current_segment: '',
    is_enabled: true
})

const ipConfigFormRef = ref()

const ipConfigRules = {
    workshop: [
        { required: true, message: '请输入车间名称', trigger: 'blur' },
        { min: 1, max: 100, message: '车间名称长度在 1 到 100 个字符', trigger: 'blur' }
    ],
    line: [
        { required: true, message: '请输入线别', trigger: 'blur' },
        { min: 1, max: 100, message: '线别长度在 1 到 100 个字符', trigger: 'blur' }
    ],
    ip: [
        { required: true, message: '请输入IP地址', trigger: 'blur' },
        {
            pattern: /^(\d{1,3}\.){3}\d{1,3}$/,
            message: '请输入正确的IP地址格式',
            trigger: 'blur'
        }
    ],
    database_path: [
        { required: true, message: '请输入数据库路径', trigger: 'blur' }
    ],
    segment_path: [
        { required: true, message: '请输入分档路径', trigger: 'blur' }
    ],
    current_segment: [
        { required: true, message: '请输入在用分档', trigger: 'blur' }
    ]
}

// 获取车间列表
const fetchWorkshops = async () => {
    try {
        const response = await axios.get('/api/ip-configs/workshops')
        workshops.value = response.data.workshops
    } catch (error) {
        console.error('获取车间列表失败:', error)
    }
}

// 获取IP配置列表
const fetchIpConfigs = async () => {
    loading.value = true
    try {
        const params = {
            page: pagination.page,
            per_page: pagination.per_page,
            search: searchForm.search,
            workshop: searchForm.workshop
        }

        const response = await axios.get('/api/ip-configs', { params })
        ipConfigs.value = response.data.ip_configs
        pagination.total = response.data.total
        pagination.pages = response.data.pages
    } catch (error) {
        ElMessage.error('获取IP配置列表失败: ' + (error.response?.data?.message || error.message))
    } finally {
        loading.value = false
    }
}

// 搜索
const handleSearch = () => {
    pagination.page = 1
    fetchIpConfigs()
}

// 重置搜索
const resetSearch = () => {
    searchForm.search = ''
    searchForm.workshop = ''
    pagination.page = 1
    fetchIpConfigs()
}

// 分页
const handleSizeChange = (val) => {
    pagination.per_page = val
    pagination.page = 1
    fetchIpConfigs()
}

const handleCurrentChange = (val) => {
    pagination.page = val
    fetchIpConfigs()
}

// 选择变化
const handleSelectionChange = (val) => {
    selectedIpConfigs.value = val
}

// 编辑IP配置
const editIpConfig = (config) => {
    editingIpConfig.value = config
    ipConfigForm.workshop = config.workshop
    ipConfigForm.line = config.line
    ipConfigForm.ip = config.ip
    ipConfigForm.database_path = config.database_path
    ipConfigForm.segment_path = config.segment_path
    ipConfigForm.current_segment = config.current_segment
    ipConfigForm.is_enabled = config.is_enabled
    showAddDialog.value = true
}

// 删除IP配置
const deleteIpConfig = async (config) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除车间"${config.workshop}"线别"${config.line}"的IP配置吗？`,
            '删除确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        await axios.delete(`/api/ip-configs/${config.id}`)
        ElMessage.success('删除成功')
        fetchIpConfigs()
        fetchWorkshops() // 更新车间列表
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message))
        }
    }
}

// 批量删除
const batchDelete = async () => {
    try {
        await ElMessageBox.confirm(
            `确定要删除选中的 ${selectedIpConfigs.value.length} 个IP配置吗？`,
            '批量删除确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        const ids = selectedIpConfigs.value.map(c => c.id)
        await axios.delete('/api/ip-configs/batch', { data: { ids } })
        ElMessage.success('批量删除成功')
        fetchIpConfigs()
        fetchWorkshops() // 更新车间列表
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('批量删除失败: ' + (error.response?.data?.message || error.message))
        }
    }
}

// 提交IP配置表单
const submitIpConfig = async () => {
    if (!ipConfigFormRef.value) return

    await ipConfigFormRef.value.validate(async (valid) => {
        if (valid) {
            submitLoading.value = true
            try {
                const data = { ...ipConfigForm }

                if (editingIpConfig.value) {
                    await axios.put(`/api/ip-configs/${editingIpConfig.value.id}`, data)
                    ElMessage.success('更新成功')
                } else {
                    await axios.post('/api/ip-configs', data)
                    ElMessage.success('创建成功')
                }

                showAddDialog.value = false
                fetchIpConfigs()
                fetchWorkshops() // 更新车间列表
            } catch (error) {
                ElMessage.error((editingIpConfig.value ? '更新' : '创建') + '失败: ' + (error.response?.data?.message || error.message))
            } finally {
                submitLoading.value = false
            }
        }
    })
}

// 重置表单
const resetForm = () => {
    editingIpConfig.value = null
    ipConfigForm.workshop = ''
    ipConfigForm.line = ''
    ipConfigForm.ip = ''
    ipConfigForm.database_path = ''
    ipConfigForm.segment_path = ''
    ipConfigForm.current_segment = ''
    ipConfigForm.is_enabled = true
    ipConfigFormRef.value?.resetFields()
}

onMounted(() => {
    fetchIpConfigs()
    fetchWorkshops()
})
</script>

<style scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.search-area {
    margin-bottom: 20px;
}

.batch-actions {
    margin: 20px 0;
}

.pagination {
    margin-top: 20px;
    text-align: right;
}
</style>